import 'dart:async';
import 'dart:typed_data';

import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:sgy_flutter/ble/base_ble_manager.dart';
import 'package:sgy_flutter/ble/base_service.dart';
import 'package:sgy_flutter/ble/relay_stream_controller.dart';
import 'package:sgy_flutter/model/axo_data_model.dart';
import 'package:sgy_flutter/model/cycling_power_measurement_resp.dart';

/** Cycling Power Measurement
 * AXO魔改协议
 **/
class CyclingPowerService16 extends BaseService {
  static const _ServiceGuid = "00001816-0000-1000-8000-00805f9b34fb";

  static const _CyclingPowerMeasurementGuid =
      "00002a5b-0000-1000-8000-00805f9b34fb";

  static const _CyclingPowerControlPointGuid =
      "00002a66-0000-1000-8000-00805f9b34fb";

  CyclingPowerService16()
      : super(
            serviceGuid: _ServiceGuid,
            characteristicNotifyGuid: _CyclingPowerMeasurementGuid,
            characteristicReadGuid: null,
            characteristicWriteGuid: null);

  RelayStreamController<AxoDataModel?> resp =
      RelayStreamController(value: null);

  @override
  Future onCleanup() async {
    tp = 0;
    time = 0;
    resp.add(AxoDataModel(power: '--', cadence: '--', balance: '--'));
  }

  int tp = 0;
  int time = 0;

  @override
  FutureOr handleNotifyData(Uint8List data) {
    final byteData = data.buffer.asByteData();
    int currentTp = byteData.getUint16(1, Endian.little);
    int currentTime = byteData.getUint16(3, Endian.little);
    String cadence = "0";
    if (tp == 0 && time == 0) {
      time = currentTime;
      tp = currentTp;
    } else {
      if (currentTp - tp == 0) {
        cadence = ("0");
      } else {
        int myTp = (((currentTime - time < 0
                ? currentTime - time + 65536
                : currentTime - time) ~/
            (currentTp - tp)));
        if (myTp != 0) {
          cadence = "${61440 ~/ myTp}";
        }

        time = currentTime;
        tp = currentTp;
      }
    }
    printInfo(info: "handleNotifyData:${cadence}");
    this
        .resp
        .add(AxoDataModel(power: "--", cadence: cadence, balance: "--"));
  }
}
